﻿using System.Net;
using System.Net.Sockets;
using Fvs_Service.Net;

namespace Fvs_Service
{
    public class LampHandler:ISocketHandler
    {
        /// <summary>
        /// 协议头字节
        /// </summary>
        private const byte HeadTag = 0x90;

        /// <summary>
        /// 协议尾字节
        /// </summary>
        private const byte TailTag = 0xFF;

        public SocketPack Unpack(Socket socket, IPEndPoint remoteEndPoint, List<byte> buffer, int offset)
        {
            int head = buffer.FindIndex(offset, b => b == HeadTag);

            if (head == -1)
            {
                //未找到协议
                return new SocketPack
                {
                    Result = AnalysisResult.Empty,
                    Offset = offset,
                    Size = buffer.Count-offset
                };
            }
            else
            {
                //半包
                int tail = buffer.FindIndex(head, b => b == TailTag);
                if (tail == -1)
                {
                    return new SocketPack
                    {
                        Result = AnalysisResult.Half,
                        Offset = head,
                        Size = buffer.Count-head
                    };
                }
                else
                {
                    return new SocketPack
                    {
                        Result = AnalysisResult.Full,
                        Offset = head,
                        Size = tail - head + 1,
                        ProtocolId = buffer[head + 2],
                        TimeStamp = 0
                    };
                }
            }
        }
    }
}
